package org.jeecg.modules.mqtt;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
public class MqttConfig {

    @Value("${mqtt.broker}")
    private String broker;

    @Value("${mqtt.client-id}")
    private String clientId;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.topic-prefix:test}")
    private String topicPrefix;

    /**
     * 配置MQTT连接选项
     * @return
     */
    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{broker});
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        // 设置连接超时时间
        options.setConnectionTimeout(30);
        // 设置心跳间隔
        options.setKeepAliveInterval(60);
        return options;
    }

    /**
     * 创建MQTT客户端工厂
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(mqttConnectOptions());
        return factory;
    }

    /**
     * 配置消息通道
     * @return
     */
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    /**
     * 配置出站消息通道
     * @return
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 配置消息适配器（用于订阅）
     * @return
     */
    @Bean
    public MqttPahoMessageDrivenChannelAdapter mqttInboundAdapter() {
        // 创建适配器，指定客户端ID、客户端工厂和要订阅的主题
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(
                        clientId + "_inbound",
                        mqttClientFactory(),
                        topicPrefix + "/#"  // 这里填写要订阅的主题
                );

        // 设置服务质量(QoS)
        adapter.setQos(1);
        // 设置消息通道
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    /**
     * 配置出站适配器（用于发送消息）
     * @return
     */
    @Bean
    public MqttPahoMessageHandler mqttOutboundHandler() {
        MqttPahoMessageHandler handler = new MqttPahoMessageHandler(clientId + "_outbound", mqttClientFactory());
        handler.setAsync(true);
        handler.setDefaultTopic(topicPrefix);
        return handler;
    }

    /**
     * 配置出站消息处理器
     * @return
     */
    @Bean
    @org.springframework.integration.annotation.ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutboundMessageHandler() {
        return mqttOutboundHandler();
    }

}
